import React from 'react'

import { Spin, Alert, Pagination } from 'antd';

import GoodsItem from './goodsItem.jsx'

export default class GoodsList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      goods: [],
      cid: props.match.params.cid,
      pagenum: parseInt(props.match.params.page) || 1,
      pagesize: 10,//每页显示条数
      total: 0,
      isLoading: true,//是否正在加载
    }
  }
  componentDidMount() {
    this.getGoodsList();

  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    this.setState({
      isLoading: true,
      pagenum: parseInt(nextProps.match.params.page) || 1,
      cid: nextProps.match.params.cid,
    }, () => {
      this.getGoodsList();
    })
    return true
  }



  render() {
    return <div>
      {this.state.isLoading ? this.loading() : this.renderList()}
    </div>
  }

  loading = () => {
    return <Spin tip="Loading...">
      <Alert
        message="正在请求商品列表"
        description="精彩内容马上呈现..."
        type="info"
      />
    </Spin>
  }

  renderList = () => {
    return <div>
      <div style={{ display: "flex", flexWrap: 'wrap', }}>
        {this.state.goods.map((item, index) => {
          return <GoodsItem key={item.goods_id} {...item}></GoodsItem>
        })}
      </div>
      <Pagination style={{ padding: '0 5px' }} defaultCurrent={this.state.pagenum} defaultPageSize={this.state.pagesize} total={this.state.total} onChange={this.onChange} />
    </div>

  }
  onChange = (page) => {
    // window.location.href='/#/goods/'+this.state.cid+'/'+page;
    this.props.history.push('/goods/' + this.state.cid + '/' + page)

  }
  getGoodsList = () => {
    const url = `https://api-hmugo-web.itheima.net/api/public/v1/goods/search?cid=${this.state.cid}&pagenum=${this.state.pagenum}&pagesize=${this.state.pagesize}`;
    fetch(url).then(res => {

      return res.json()
    }).then(data => {
      if (data.meta.status === 200) {
        this.setState({
          isLoading: false,
          goods: data.message.goods,
          total: data.message.total,
        })
      }

    })
  }



}